<template>
  <div class="user">
    <pageSearch
      :searchFormConfig="searchFormConfig"
      @queryBtnClick="queryBtnClick"
      @resetBtnClick="resetBtnClick"
    />
    <pageContent
      ref="pageContentRef"
      :contentTableConfig="contentTableConfig"
      pageName="users"
      title="新增用户"
      @newBtnClick="newBtnClick"
      @editBtnClick="editBtnClick"
    ></pageContent>
    <page-model
      :modelConfig="modelConfigRef"
      title="新增用户"
      ref="pageModelRef"
      pageName="users"
      :defaultInfo="defaultInfo"
    ></page-model>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent } from 'vue'
import { useStore } from '@/store'

import { searchFormConfig } from './config/search.config'
import { contentTableConfig } from './config/content.config'
import { modelConfig } from './config/model.config'

import pageSearch from '@/components/page-search'
import pageContent from '@/components/page-content'
import pageModel from '@/components/page-model'

import { usePageSearch } from '@/hooks/usePageSearch'
import { usePageModel } from '@/hooks/usePageModel'

export default defineComponent({
  name: 'user',
  components: {
    pageSearch,
    pageContent,
    pageModel
  },
  setup() {
    // 封装searchpage中的逻辑封装
    const { pageContentRef, queryBtnClick, resetBtnClick } = usePageSearch()

    // 获取部门和角色的数据，因为想要是响应式的，所以就对modelConfig做一个计算属性，因为store中的
    // entireDepartment和entireRole只要请求回来数据后，会更新modelConfig，所以就把最新的数据放到modelConfigRef中
    const store = useStore()
    const modelConfigRef = computed(() => {
      const departmentItem = modelConfig.formItems.find((item) => {
        return item.field === 'departmentId'
      })
      departmentItem!.options = store.state.entireDepartment.map(
        (item: any) => {
          return { label: item.name, value: item.id }
        }
      )

      const roleItem = modelConfig.formItems.find(
        (item) => item.field === 'roleId'
      )
      roleItem!.options = store.state.entireRole.map((item: any) => {
        return { label: item.name, value: item.id }
      })

      return modelConfig
    })

    // 因为在编辑的时候需要隐藏密码的输入框
    const newCallback = () => {
      const passwordItem = modelConfig.formItems.find(
        (item) => item.field === 'password'
      )
      passwordItem!.isHidden = false
    }
    const editCallback = () => {
      const passwordItem = modelConfig.formItems.find(
        (item) => item.field === 'password'
      )
      passwordItem!.isHidden = true
    }
    // 封装pageModel中的操作逻辑的hooks
    const { pageModelRef, defaultInfo, newBtnClick, editBtnClick } =
      usePageModel(newCallback, editCallback)

    return {
      searchFormConfig,
      contentTableConfig,
      modelConfigRef,
      pageContentRef,
      queryBtnClick,
      resetBtnClick,
      newBtnClick,
      editBtnClick,
      pageModelRef,
      defaultInfo
    }
  }
})
</script>

<style scoped lang="less"></style>
